package com.jt.www.admin.order_pc.service.impl;

import com.alibaba.fastjson.JSON;
import com.jt.www.admin.order_pc.service.PromoteBusinessService;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.model.reps.ResponseData;
import com.jt.www.model.vo.InsManagerQo;
import com.jt.www.model.vo.promoteBusiness.IndexVo;
import com.jt.www.model.vo.promoteBusiness.MsgVo;
import com.jt.www.remote.UserClient;
import com.jt.www.remote.ins.InsClient;
import com.jt.www.util.DateUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@Service
public class PromoteBusinessServiceImpl implements PromoteBusinessService {

    public static final Logger log = LoggerFactory.getLogger(PromoteBusinessServiceImpl.class);
    private final static String CHANNEL_CODE = "edu";
    private final static String CHANNEL_TYPE_00 = "00";// 教保网
    private final static String CHANNEL_TYPE_02 = "02";// 我学保
    private final static String SYS_CODE = "sys_edu_man";
    private final static String APP_STATUS_18 = "18";// 18-已提交；02-待复审；
    private final static String APP_STATUS_02 = "02";// 18-已提交；02-待复审；
    @Autowired
    private InsClient insClient;
    @Autowired
    private UserClient userClient;

    @Override
    public ResponseEntity promoteBusinessIndex(String userCode) throws Exception {

        if (StringUtils.isBlank(userCode)) {
            return GenericDataResponse.errorWithMsg("参数不能为空");
        }

        IndexVo vo = new IndexVo();

        Integer orgNum = 0;// 待审核机构数量
        Integer polNumCs = 0;// 待审核（已提交、待复审）保单数量
        Integer polNumFs = 0;// 待审核（已提交、待复审）保单数量
        Integer taskNum = 0;// 待办任务 taskNum = polNumCs + polNumFs + orgNum
        Integer renewalNum = 0;// 待续保 教保网
        Integer wxbRenewalNum = 0;// 待续保 我学保

        //#####################################待审核认证用户###########################################################################################

        //请求用户中心
        ResponseEntity<GenericDataResponse<Map<String, Object>>> responseEntity = userClient.queryUserRoleAndAuthority(userCode, SYS_CODE);
        LinkedHashMap<String, String> dataPopedom = (LinkedHashMap) responseEntity.getBody().getData().get("dataPopedom");
        // 获取区域码, 可能是城市码,省编码,  多个值是以逗号隔开
        String dataArea = dataPopedom.get("dataArea");

        String jtBranchs = dataPopedom.get("jtBranchs");

        // 1.调用用户中心查询待审核机构数量
        Map<String, Object> orgMap = new HashMap<>();
        orgMap.put("auditStatus", "0");
        orgMap.put("pageNum", 0);
        orgMap.put("pageSize", 0);
        if (!"000000".equals(dataArea)) {//进入分支机构
            orgMap.put("areaCode", dataArea);
        }
        GenericListResponse<Map<String, Object>> orgResp = userClient.eduOrgList(orgMap);

        if ("0000".equals(orgResp.getCode())) {
            orgNum = Integer.valueOf(String.valueOf(orgResp.getTotal()));
        }
        // 待审核注册信息
        vo.setOrgNum(orgNum);

        //#####################################已提交、待复审保单数量###########################################################################################

        // 2.调用投保中心查询待审核保单数量
        Map<String, Object> insMap = new HashMap<>();
        //若dataArea为000000  则表示全国
        if (!"000000".equals(dataArea)) {//进入分支机构
            Map<String, Object> areaMap = setProAndCityCode(dataArea);
            insMap.put("provinceCode", areaMap.get("province") != null ? areaMap.get("province").toString() : "");
            insMap.put("cityCode", areaMap.get("city") != null ? areaMap.get("city").toString() : "");
        }

        insMap.put("appStatus", APP_STATUS_18);// 已提交
        log.info("展业端首页待办任务查询接口 待审核保单数量入参 {}", JSON.toJSON(insMap));
        ResponseData insResult = insClient.selectEduAuditAppNum(JSON.toJSONString(insMap));
        if ("0000".equals(insResult.getCode())) {
            polNumCs = Integer.valueOf(insResult.getData().toString());
        }
        // 已提交保单
        vo.setPolNumCs(polNumCs);

        insMap.put("appStatus", APP_STATUS_02);// 待复审
        log.info("展业端首页待办任务查询接口 待审核保单数量入参 {}", JSON.toJSON(insMap));
        ResponseData insResult02 = insClient.selectEduAuditAppNum(JSON.toJSONString(insMap));
        if ("0000".equals(insResult02.getCode())) {
            polNumFs = Integer.valueOf(insResult02.getData().toString());
        }
        // 待复审保单
        vo.setPolNumFs(polNumFs);

        log.info("展业端首页待办任务查询接口 待审核机构数量 {}，待初审(已提交)投保单数量 {}，待复审(待复审)投保单数量 {}", orgNum, polNumCs, polNumFs);

        //待办任务
        taskNum = orgNum + polNumCs + polNumFs;
        vo.setTaskNum(taskNum);

        //####################################滚动信息############################################################################################

        // 3.调用投保中心查询滚动信息
        String linkName = "";// 分公司联系人名称 只显示 张** 形式
        GenericDataResponse<MsgVo> msgResult = insClient.selectEduPromoteBussnessMsg();
        if ("0000".equals(msgResult.getCode()) && msgResult.getData() != null) {
            GenericListResponse<Map<String, Object>> linkResult = userClient.queryContactPerson(CHANNEL_CODE, msgResult.getData().getBranchCode(), null, null, null);
            if ("0000".equals(linkResult.getCode()) && linkResult.getList().size() > 0) {
                linkName = linkResult.getList().get(0).get("linkmanName").toString();
                linkName = StringUtils.isNotBlank(linkName) ? linkName.substring(0, 1).concat("**") : "";
            }
            // 投保日期 = 今天，显示 今天 HH:mm
            // 投保日期 != 今天，显示 MM-dd HH:mm
            String applicationDate = msgResult.getData().getApplicationDate();
            if (DateUtils.isToday(DateUtils.convertTimeToLong(msgResult.getData().getApplicationDate()))) {
                applicationDate = "今天 " + DateUtils.formattedDateTime(applicationDate, DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, DateUtils.DATE_FORMAT_HHMI);
            } else {
                applicationDate = DateUtils.formattedDateTime(applicationDate, DateUtils.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, DateUtils.DATE_FORMAT_MMDDHHMI);
            }
            String msg = applicationDate + " " + msgResult.getData().getBranchName() + " " + linkName + "已出1单 "
                    + msgResult.getData().getProductName() + " " + msgResult.getData().getActualPrem() + "元";

            // 滚动信息
            vo.setRollingInfo(msg);
        }

        //#################################应收###############################################################################################

        // 应收 - 目前需求尚不确定，默认返回0
        vo.setReceiveAmount(0.0);

        //#################################待续保###############################################################################################

        // 待续保
        InsManagerQo qo = new InsManagerQo();
        if (!"000000".equals(dataArea)) {//进入分支机构
            Map<String, Object> areaMap = setProAndCityCode(dataArea);
            qo.setProvinceCode(areaMap.get("province") != null ? areaMap.get("province").toString() : "");
            qo.setCityCode(areaMap.get("city") != null ? areaMap.get("city").toString() : "");
        }
        qo.setPn(0);
        qo.setPs(0);
        qo.setChannelType(CHANNEL_TYPE_00);
        ResponseData rets = insClient.selectEduPcRenewalList(JSON.toJSONString(qo));

        if (null != rets && null != rets.getList()) {
            renewalNum = Integer.valueOf(String.valueOf(rets.getTotal()));
        }
        vo.setRenewalNum(renewalNum);

        qo.setChannelType(CHANNEL_TYPE_02);
        rets = insClient.selectEduPcRenewalList(JSON.toJSONString(qo));

        if (null != rets && null != rets.getList()) {
            wxbRenewalNum = Integer.valueOf(String.valueOf(rets.getTotal()));
        }
        vo.setWxbRenewalNum(wxbRenewalNum);

        return GenericDataResponse.okWithData(vo);
    }

    /**
     * 设置省,市编码
     *
     * @param dataArea 用户中心返回的省市编码
     */
    private Map setProAndCityCode(String dataArea) {
        //
        StringBuffer buffProvinceCode = new StringBuffer();
        StringBuffer buffCityCode = new StringBuffer();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(dataArea)) {
            String[] dataAreas = dataArea.split(",");
            for (String code : dataAreas) {
                //String subCode = code.substring(code.length()-4, code.length()) ;
                if (code.endsWith("0000")) {//代表是省编码
                    buffProvinceCode.append(code).append(",");
                } else {//市编码
                    buffCityCode.append(code).append(",");
                }
            }
        }
        String provinceCode = "";
        String cityCode = "";
        if (buffProvinceCode.length() > 0) {
            provinceCode = buffProvinceCode.substring(0, buffProvinceCode.length() - 1);
        }
        if (buffCityCode.length() > 0) {
            cityCode = buffCityCode.substring(0, buffCityCode.length() - 1);
        }

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("province", provinceCode);
        map.put("city", cityCode);
        return map;
    }
}
